<template>
  <div style="height: 800px; margin: 2vw">
    <div class="main-header">
      昵称:<el-input
        type="text"
        placeholder="请输入内容"
        style="margin-right: 5vw; margin-left: 1vw;width: 200px;"
        v-model="queryName"
    />
      账号:<el-input
        type="text"
        placeholder="请输入内容"
        style="margin-right: 5vw; margin-left: 1vw;width: 200px;"
        v-model="queryAccount"
    />
      <el-button type="primary" @click="check">查询</el-button>
      <el-button type="primary" style="float: right; margin-right: 5vw" @click="openAddOrUpdate('add', null)">新增
      </el-button>

      <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible">
        <el-form :model="form">
          <div class="upload">
            <span style="margin-right: 5vw;line-height: 100px">头 像</span>
            <el-upload
                class="avatar-uploader"
                :headers="{accessToken}"
                :show-file-list="false"
								:http-request="myUpload"
								action=""
            >
              <img v-if="form.profileImg" :src="form.profileImg" class="avatar" alt="">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </div>
          <el-form-item label="账号" label-width=120px>
            <el-input style="width: 35vw" v-model="form.account" :disabled="dialogDisabled"></el-input>
          </el-form-item>
          <el-form-item label="昵称" label-width=120px>
            <el-input style="width: 35vw" v-model="form.name"></el-input>
          </el-form-item>
          <el-form-item label="地区" label-width=120px>
            <van-field
                readonly
                clickable
                name="location"
                :value="form.location"
                placeholder="点击选择省市区"
                @click="form.showArea = true"
            />
            <van-popup v-model="form.showArea" position="bottom">
              <van-area
                  :area-list="form.areaList"
                  @confirm="onConfirm"
                  @cancel="form.showArea = false"
              />
            </van-popup>
          </el-form-item>
          <el-form-item label="性别" label-width=120px>
            <el-radio v-model="form.gender" label="0">男</el-radio>
            <el-radio v-model="form.gender" label="1">女</el-radio>
          </el-form-item>
          <el-form-item label="个性签名" label-width=120px>
            <el-input style="width: 35vw" v-model="form.profileText"></el-input>
          </el-form-item>
          <div class="upload">
            <span style="margin-right: 5vw;line-height: 100px">背景图</span>
            	<el-upload
                class="avatar-uploader"
                :headers="{accessToken}"
                :show-file-list="false"
								:http-request="myUploadBack"
								action=""
							>
              <img v-if="form.backgroundImg" :src="form.backgroundImg" class="avatar" alt="">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </div>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="dialogDisabled ? updateUser() : addUser()">保 存</el-button>
        </div>
      </el-dialog>
    </div>
    <div>
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column fixed label="序号" width="50" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.num }}</span>
          </template>
        </el-table-column>
        <el-table-column label="昵称" min-width="100" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="账号" min-width="100" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.account }}</span>
          </template>
        </el-table-column>
        <el-table-column label="地区" min-width="100" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.location }}</span>
          </template>
        </el-table-column>
        <el-table-column label="性别" width="50" align="center">
          <template slot-scope="scope">
            <span>{{ Number(scope.row.gender) === 0 ? " 男" : "女" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" min-width="150" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.createTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="修改时间" min-width="150" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.updateTime }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" min-width="200" align="center">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="resetPwd(scope.$index)">重置密码</el-button>
            <el-button type="text" size="small" @click="openAddOrUpdate('update', scope.row)">编辑</el-button>
            <el-button type="text" size="small" v-if="!scope.row.isAdmin" @click="updateAdmin(scope.$index)">管理授权
            </el-button>
            <el-button type="text" size="small" v-else @click="updateAdmin(scope.$index)" style="color: firebrick">
              取消授权
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div style="float: right; margin-top: 10vh">
      <el-pagination
          background
          :page-size="size"
          layout="sizes, prev, pager, next,jumper"
          :page-sizes="[10]"
          :total="total"
          @current-change="upPage"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import store from "../store";
import {areaList} from '@vant/area-data';


export default {
  data() {
    return {
      accessToken:store.state.token,
      dialogTitle: "",
      dialogFormVisible: false,
      dialogDisabled: true,
      form: {
        id: '',
        account: '',
        name: '',
        location: '',
        gender: "0",
        profileImg: "",
        profileText: '',
        backgroundImg: "",
        showArea:false,
        areaList,
      },

      queryName: "",
      queryAccount: "",
      tableData: [
        {
          account: "",
          backgroundImg: "",
          createTime: "",
          gender: "",
          id: "",
          isAdmin: false,
          location: "",
          name: "",
          profileImg: "",
          profileText: "",
          updateTime: "",
          num: 0,
        },
      ],
      size: 10,
      current: 1,
      total: 0,
      pages: 0,
    };
  },
  methods: {
    onConfirm(values) {
      this.form.location = values
          .filter((item) => !!item)
          .map((item) => item.name)
          .join('/');
      this.form.showArea = false;
    },
    //修改管理员状态
    updateAdmin(index) {
      let url = `/api/lzs/user/admin?type=${this.tableData[index].isAdmin ? 0 : 1}&userId=${this.tableData[index].id}`
      this.http.get(url).then((res) => {
        this.$message.success(res.data.message);
        this.check();
      });
    },
    //重置密码
    resetPwd(index) {
      // console.log(index, row)
      this.$confirm('确定重置密码?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: "warning"
      }).then(() => {
        let url = `/api/lzs/user/reset?userId=${this.tableData[index].id}`
        this.http.get(url).then((res) => {
          this.$message.success(res.data.message);
        })
      }).catch(() => {
        this.$message.info('已取消重置密码');
      })
    },

    //更新页码
    upPage(val) {
      this.current = val;
      this.check();
    },

    //查询用户
    check() {
      let url = "/api/lzs/user/page";
      let params = {
        account: this.queryAccount,
        currentPage: this.current,
        name: this.queryName,
        pageSize: this.size
      };
      this.http.post(url, params).then((res) => {
        let data = res.data.data;
        this.total = data.total;
        this.pages = data.pages;
        this.size = data.size;
        this.current = data.current;
        this.tableData = [];
        for (let i in data.records) {
          let temp = {
            id: data.records[i].id,
            num: (Number(this.current) - 1) * Number(this.size) + 1 + Number(i),
            name: data.records[i].name,
            account: data.records[i].account,
            createTime: data.records[i].createTime,
            updateTime: data.records[i].updateTime,
            backgroundImg: data.records[i].backgroundImg,
            gender: data.records[i].gender.toString(),
            isAdmin: data.records[i].isAdmin,
            location: data.records[i].location,
            profileImg: data.records[i].profileImg,
            profileText: data.records[i].profileText,
          };
          this.tableData.push(temp);
        }
      });
    },

    //上传头像,背景图
    afterReadPro(file) {
      this.form.profileImg = file.data;
    },
    afterReadBack(file) {
      this.form.backgroundImg = file.data;
    },
    //添加用户
    addUser() {
      let url = "/api/lzs/user/add";
      let params = {
        account: this.form.account,
        backgroundImg: this.form.backgroundImg,
        gender: this.form.gender,
        location: this.form.location,
        name: this.form.name,
        profileImg: this.form.profileImg,
        profileText: this.form.profileText
      };
      this.http.post(url, params).then(() => {
        this.dialogFormVisible = false
        this.$message.success("新增成功")
      });
    },

    // 编辑用户
    updateUser() {
      let url = '/api/lzs/user/update'
      let params = {
        account: this.form.account,
        backgroundImg: this.form.backgroundImg,
        gender: this.form.gender,
        id: this.form.id,
        location: this.form.location,
        name: this.form.name,
        profileImg: this.form.profileImg,
        profileText: this.form.profileText
      };
      this.http.post(url, params).then(() => {
        this.dialogFormVisible = false;
        this.$message.success("修改成功")
        this.check();
      })
    },

    //打开方法
    openAddOrUpdate(type, record) {
      if (type === "add") {
        this.dialogTitle = "新增";
        this.dialogDisabled = false;
        this.form.id = "";
        this.form.account = "";
        this.form.name = "";
        this.form.location = "";
        this.form.gender = "0";
        this.form.profileImg= "";
        this.form.profileText = "";
        this.form.backgroundImg = "";
      } else if (type === "update") {
        this.dialogTitle = "编辑";
        this.dialogDisabled = true;
        this.form.id = record.id;
        this.form.account = record.account;
        this.form.name = record.name;
        this.form.location = record.location;
        this.form.gender = record.gender;
        this.form.profileText = record.profileText;
        this.form.backgroundImg = record.backgroundImg;
        this.form.profileImg = record.profileImg;
      }
      this.dialogFormVisible = true;
    },
		myUpload(file) {
			let url = '/api/lzs/file/upload'
			const fd = new FormData();
			fd.append('file', file.file);
			this.http.post(url, fd).then((res) => {
				this.form.profileImg = res.data.data;
			})
		},
		myUploadBack(file) {
			let url = '/api/lzs/file/upload'
			const fd = new FormData();
			fd.append('file', file.file);
			this.http.post(url, fd).then((res) => {
				this.form.backgroundImg = res.data.data;
			})
		},
  },
  mounted() {
    this.check();
  },
};
</script>

<style scoped>

.upload {
  padding-left: 80px;
  display: flex;
  margin-bottom: 2vh;
}
.main-header{
  margin-bottom: 1vh;
}
.avatar-uploader{
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  display: inline-block;
}
.avatar-uploader:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  border-radius: 6px;
  border: 1px dashed darkgray;
}
.avatar {
  width: 100px;
  height: 100px;
  display: inline-block;
}
</style>
